<template>
  <a-card title="组织列表" :bordered="false" class="result-card mt-20">
    <template #extra>
      <a-button type="primary" @click="handlePopCreateRootModal">添加组织</a-button>
    </template>
    <div class="tree-content">
      <a-tree :tree-data="departmentList" :selectable="false" :field-names="{children:'child', title:'name', key:'code'}">
        <template #title="node">
          <div class="node-row flex align-center">
            <span>{{node.name}}</span>
            <a-button class="ml-12" type="link" @click="handlePopCreateModal(node)">
              <i class="iconfont icon-xinzeng"></i>
            </a-button>
            <a-button class="ml-12" type="link" @click="handlePopEditModal(node)">
              <i class="iconfont icon-bianji"></i>
            </a-button>
            <a-popconfirm
                title="确定要删除吗?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelRecord(node)">
              <a-button class="ml-12" type="link" danger>
                <i class="iconfont icon-shanchu"></i>
              </a-button>
            </a-popconfirm>
          </div>
        </template>
      </a-tree>
    </div>
  </a-card>
  <a-modal :width="520" :title="editMode ? '编辑组织信息' : '添加组织信息'" v-model:visible="modalVisible" :confirmLoading="saveLoading" @ok="handleSave">
    <a-form
        layout="vertical"
        :model="formState"
        :rules="rules"
        ref="formRef">
      <a-form-item
          label="组织名称"
          name="name">
        <a-input v-model:value="formState.name" placeholder="请输入组织名称"></a-input>
      </a-form-item>
      <a-form-item
          label="组织编号"
          name="code">
        <a-input disabled v-model:value="formState.code" placeholder="请输入组织编号"></a-input>
      </a-form-item>
      <a-form-item
          label="父组织"
          name="parentCode">
        <a-tree-select
            v-model:value="formState.parentCode"
            show-search
            :field-names="{children:'child', label:'name', value:'code'}"
            placeholder="请选择"
            allow-clear
            tree-default-expand-all
            :tree-data="filterDepartmentList"
            treeNodeLabelProp="name"
            tree-node-filter-prop="name"></a-tree-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import {nextTick, reactive, ref} from "vue";
import api from '../../api/departments'
import {DepartmentItem} from '../../types/common'
import {UserTypes, UserTypesObj, UserSex} from '../../common/constants'
import {uuid, loopTree} from '../../common/utils'
import {message} from "ant-design-vue";
const modalVisible = ref<boolean>(false)
const editMode = ref<boolean>(false)
const defFormState = {
  name: '',
  code: '',
  parentCode: ''
}
const formState = ref({...defFormState})
const formRef = ref()
const rules = {
  name: [
    { required: true, trigger: 'blur', message: '请输入组织名称' },
  ],
}
const saveLoading = ref<boolean>(false)
const departmentList = ref<DepartmentItem[]>([])
const filterDepartmentList = ref<DepartmentItem[]>([])
const getTreeData = async () => {
  departmentList.value = []
  try {
    const res = await api.getList()
    if (res.content && res.content.length) {
      departmentList.value = res.content
    }
  } catch(e: any) {
  }
}

getTreeData()
const handleSave = async () => {
  try {
    await formRef.value.validateFields()
    console.log('formState', formState.value)
    saveLoading.value = true
    let res
    if (!editMode.value) {
      res = await api.create(formState.value)
    } else {
      res = await api.edit(formState.value)
    }
    saveLoading.value = false
    if (res.success) {
      if (!editMode.value) {
        message.success('组织添加成功')
        getTreeData()
      } else {
        message.success('组织修改成功')
        getTreeData()
      }
      modalVisible.value = false
    } else {
      let msg = '操作失败'
      if (res.errors && res.errors[0] && res.errors[0].message) {
        msg = res.errors[0].message
      }
      message.error(msg)
    }
  }catch(e){
    saveLoading.value = false
    if (e.errors && e.errors[0] && e.errors[0].message) {
      message.error(e.errors[0].message)
    }
    console.log(e)
  }
}
const handlePopCreateRootModal = () => {
  formState.value = {...defFormState}
  formState.value.code = uuid(8, 0, '0123456789')
  formState.value.parentCode = ''
  filterDepartmentList.value = JSON.parse(JSON.stringify(departmentList.value))
  editMode.value = false;
  modalVisible.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
}
const handlePopCreateModal = (item: DepartmentItem) => {
  formState.value = {...defFormState}
  formState.value.code = uuid(8, 0, '0123456789')
  formState.value.parentCode = item.code
  filterDepartmentList.value = JSON.parse(JSON.stringify(departmentList.value))
  editMode.value = false;
  modalVisible.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
}
const handlePopEditModal = (item: DepartmentItem) => {
  Object.assign(formState.value, item)
  filterDepartmentList.value = JSON.parse(JSON.stringify(departmentList.value))
  loopTree(filterDepartmentList.value, 'child', (node: DepartmentItem) => {
    node.disabled = node.code === item.code
  })
  editMode.value = true;
  modalVisible.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
}
const handleDelRecord = async (item: any) => {
  try {
    const res = await api.del(item.code)
    if (res.success) {
      message.success('删除成功')
      getTreeData()
    } else {
      let msg = '操作失败'
      if (res.errors && res.errors[0] && res.errors[0].message) {
        msg = res.errors[0].message
      }
      message.error(msg)
    }
  } catch (e) {
    if (e.errors && e.errors[0] && e.errors[0].message) {
      message.error(e.errors[0].message)
    }
    console.log(e)
  }
}

</script>

<style scoped lang="less">
  .condition-col{
    .ant-input{
      min-width: 300px;
    }
    .ant-select{
      min-width: 160px;
    }
  }
  .tree-content{
    position: relative;
    max-height: calc(100vh - 180px);
  }
  .ant-btn-link{
    padding: 0;
  }
</style>
